package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
        // 获取sql的语句
        String sqlStatement = "com.leyou.item.mapper.SkuMapper.deductStock";
        try {
            // 批处理
            updateStockBatch(cartMap, sqlStatement);
        } catch (Exception e) {
            throw new LyException(500, "库存不足");
        }
        /*for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            // 减库存
            Map<String, Object> param = new HashMap<>(2);
            param.put("id", entry.getKey());
            param.put("num", entry.getValue());
            getBaseMapper().deductStock(param);
        }*/
    }

    @Override
    @Transactional
    public void addStock(Map<Long, Integer> cartMap) {
        // 获取sql的语句
        String sqlStatement = "com.leyou.item.mapper.SkuMapper.addStock";
        try {
            updateStockBatch(cartMap, sqlStatement);
        } catch (Exception e) {
            throw new LyException(500, "更新库存失败");
        }
    }

    private void updateStockBatch(Map<Long, Integer> cartMap, String sqlStatement) {
        // 批处理
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                Map<String, Object> param = new HashMap<>(2);
                param.put("id", entry.getKey());
                param.put("num", entry.getValue());
                // 编译sql
                sqlSession.update(sqlStatement, param);
            }
            // 执行
            sqlSession.flushStatements();
        });
    }
}
